let app = getApp();
// let http = require("../../utils/XRequest.js");
// let utils = require("../../utils/utils.js");

Component({
        properties: {
                goodsId: { // 属性名
                        type: String,
                        value: ''
                },
        },
        data: {
                id: 0,
                total: 0,
                num: 1,
                indexs: 0,
                goods: {},
                // 商品信息
                product: {},
                // 产品信息
                products: {},
                // 规格
                spec1: [],
                spec2All: [],
                spec2: [],
                spec1Index: -1,
                spec2Index: -1,
                quantity: 0,
                address: '',
                minusStatus: "normal",
                hide: false,
                paySn: '',
                giveId: '',
                types: 'give',
                amounts: false,
                confirm: false,
                _shippingMethod: 'shipping',
                mode: false,
                promotionType: '',
                maximum: 0,
                actIndex: 0,
                promotionTitle: "",
                showActivity: true,
                type: '',
                giveQuantity: 1,
                addCartButtonText: '立即购买'
        },
        created() {
                var _this = this;
                _this.open_cart();
                _this.onActiveChange = function(e) {
                        console.log(e)
                        _this.data.giveId = e.promotionId
                        _this.data.promotionTitle = e.promotionTitle
                        _this.data.giveQuantity = e.promotionQuantity
                        _this.data.num = e.promotionQuantity
                        _this.setData({
                                promotionTitle: _this.data.promotionTitle,
                                num: _this.data.num
                        })
                }
                //监听
                app.event.on("onActiveChange", this.onActiveChange)
        },
        detached() {
                app.event.off("onActiveChange", this.onActiveChange)
        },
        methods: {
                // 隐藏活动选择
                hiddenActivity() {
                        this.data.showActivity = false;
                        this.setData({
                                showActivity: this.data.showActivity
                        })
                },
                //选择规格
                selection: function(e) {
                        var _this = this;

                        let _type = e.currentTarget.dataset.type;
                        let _value = e.currentTarget.dataset.value;
                        var index2 = _this.data.spec2Index
                        console.log(_type, _value)
                        if (_type == "spec1") {
                                _this.data.spec1Index = _this.data.spec1.indexOf(_value);
                                _this.data.spec2Index = -1;
                                _this.data.spec2 = [];
                                _this.data.spec2All.forEach(function(sp) {
                                        _this.data.products.forEach(function(item) {
                                                if (item.spec1 == _value && item.spec2 == sp) {
                                                        _this.data.spec2.push(sp);
                                                }
                                        })
                                })

                        }
                        if (_type == "spec2") {
                                _this.data.spec2Index = _this.data.spec2.indexOf(_value);
                        }

                        //定位商品

                        _this.data.products.forEach(function(item) {
                                if (
                                        ((_this.data.spec1Index >= 0 && item.spec1 == _this.data.spec1[_this.data.spec1Index]) || _this.data.spec1Index < 0) &&
                                        ((_this.data.spec2Index >= 0 && item.spec2 == _this.data.spec2[_this.data.spec2Index]) || _this.data.spec2Index < 0)
                                ) {
                                        _this.data.product = item;
                                        console.log(item);
                                }
                        })

                        _this.setData({
                                product: _this.data.product,
                                spec1Index: _this.data.spec1Index,
                                spec2Index: _this.data.spec2Index,
                                spec2: _this.data.spec2
                        })
                        console.log(_this.data.product)
                        _this.calc();
                        console.log(_this.data.spec1Index);
                        console.log(_this.data.spec2Index);
                },
                setAddress: function(addr) {
                        var _this = this
                        _this.data.address = addr;
                        _this.setData({
                                address: _this.data.address
                        })
                        if (!utils.isNull(addr)) {
                                _this.calc();
                        }
                        console.log(_this.data.address);
                },
                show: function(id, type, path, giveId) {
                        console.log(type)
                        console.log(giveId)
                        var _this = this;
                        if (!utils.isNull(path)) {
                                // 不为空时代表该页面发起多规格有特殊需求，比如更改按钮文字
                                this.data.addCartButtonText = '立即叫水';
                                this.setData({
                                        addCartButtonText: this.data.addCartButtonText
                                })
                        }
                        if (!utils.isNull(giveId)) {
                                _this.data.giveId = giveId
                        }
                        if (utils.isNull(type)) {
                                _this.data.mode = false
                                _this.setData({
                                        goodsId: id,
                                        hide: true,
                                        num: 1,
                                        mode: _this.data.mode,
                                })
                        } else {
                                _this.data.type = type
                                _this.data.mode = true
                                _this.setData({
                                        goodsId: id,
                                        hide: true,
                                        mode: _this.data.mode,
                                        num: 1
                                })
                        }
                        console.log(_this.data.mode)
                        _this.open(id)
                },
                // 这里是一个自定义方法
                open: function(id) {
                        var _this = this;
                        _this.data.id = id;
                        http.GET('applet/product/view.jhtml?type=cart&id=' + id + '&promotionId=' + _this.data.giveId, function(res) {
                                console.log(res)
                                if (res.type == 'success') {
                                        _this.data.goods = res.data
                                        _this.data.promotions = res.data.promotions;
                                        _this.data.products = res.data.products;
                                        _this.data.spec1 = []
                                        _this.data.spec2 = []
                                        _this.data.spec2All = []

                                        //规格1去重 
                                        for (var i = 0; i < _this.data.products.length; i++) {
                                                if (!utils.isNull(_this.data.products[i].spec1)) {
                                                        var repeat = false;
                                                        for (var j = 0; j < _this.data.spec1.length; j++) {
                                                                if (_this.data.products[i].spec1 == _this.data.spec1[j]) {
                                                                        repeat = true;
                                                                        break;
                                                                }
                                                        }
                                                        if (!repeat) {
                                                                _this.data.spec1.push(_this.data.products[i].spec1);
                                                        }
                                                        console.log(_this.data.spec1)
                                                }

                                        }
                                        // 规格2去重


                                        for (var i = 0; i < _this.data.products.length; i++) {
                                                if (!utils.isNull(_this.data.products[i].spec2)) {
                                                        var repeat = false;
                                                        for (var j = 0; j < _this.data.spec2.length; j++) {
                                                                if (_this.data.products[i].spec2 == _this.data.spec2[j]) {
                                                                        repeat = true;
                                                                        break;
                                                                }
                                                        }
                                                        if (!repeat) {
                                                                _this.data.spec2.push(_this.data.products[i].spec2);
                                                                _this.data.spec2All.push(_this.data.products[i].spec2);
                                                        }
                                                }

                                        }
                                        _this.data.promotions.forEach(function(item, index) {
                                                if (index == 0) {
                                                        _this.data.giveId = item.id
                                                        _this.data.promotionTitle = item.title
                                                        if (item.quantity > 1) {
                                                                _this.data.num = item.quantity
                                                                _this.data.giveQuantity = item.quantity
                                                        }
                                                        _this.setData({
                                                                promotionTitle: _this.data.promotionTitle,
                                                                num: _this.data.num
                                                        })
                                                }
                                        })


                                        if (_this.data.maximum != 0 && _this.data.num > _this.data.maximum) {
                                                _this.data.num = _this.data.maximum
                                        }
                                        if (_this.data.goods.minimum != 0) {
                                                _this.data.num = _this.data.goods.minimum
                                        }
                                        _this.data.products.forEach(function(item) {
                                                item.Thumbnail = utils.thumbnail(item.thumbnail, 150, 150)
                                        })
                                        _this.data.product = _this.data.products[0];
                                        _this.data.spec1Index = _this.data.spec1.indexOf(_this.data.product.spec1)
                                        _this.data.spec2Index = _this.data.spec2.indexOf(_this.data.product.spec2)
                                        _this.data.hide = false;
                                        _this.setData({
                                                goods: _this.data.goods,
                                                product: _this.data.product,
                                                spec1: _this.data.spec1,
                                                spec2: _this.data.spec2,
                                                spec1Index: _this.data.spec1Index,
                                                spec2Index: _this.data.spec2Index,
                                                hide: _this.data.hide,
                                                num: _this.data.num,
                                                promotions: _this.data.promotions
                                        })

                                        _this.calc();
                                } else {
                                        wx.showToast({
                                                icon: "none",
                                                title: res.content,
                                        })
                                }
                        }, function(err) {
                                console.log(err);
                        })

                        http.GET('applet/cart/count.jhtml', function(res) {
                                if (res.type == 'success') {
                                        _this.data.quantity = res.data;
                                        _this.setData({
                                                quantity: _this.data.quantity
                                        })
                                }
                        }, function(err) {

                        })
                },
                open_view: function() {
                        var _this = this
                        http.GET("applet/member/card/view.jhtml", function(res) {
                                console.log(res)
                                if (res.type == "success") {
                                        if (res.data.status == "none") {
                                                _this.setData({
                                                        cardId: true
                                                })
                                        } else if (res.data.status == "activate") {
                                                console.log('用户点击辅助操作')
                                                _this.setData({
                                                        cardId: false
                                                })

                                        }
                                }
                        }, function(err) {
                                wx.showToast({
                                        icon: "none",
                                        title: err.content
                                })
                                return
                        })
                },
                open_cart: function() {
                        var _this = this
                        http.GET("website/cart/list.jhtml", function(res) {
                                console.log(res)
                                if (res.type == 'success') {
                                        _this.data.cart = res.data;
                                } else {
                                        wx.showToast({
                                                icon: "none",
                                                title: res.concent,
                                        })
                                }
                        })
                },
                // 检查活动
                quirey: function() {
                        let _this = this;
                        if (this.data.goods.promotions.length > 0) {
                                this.data.promotions.forEach(function(item, index) {
                                        if (_this.data.num >= item.quantity) {
                                                _this.data.giveId = item.id
                                                _this.data.promotionTitle = item.title
                                                _this.data.giveQuantity = item.quantity
                                        }
                                })
                                if (this.data.promotions.length > 0 && this.data.num < this.data.giveQuantity) {
                                        this.data.giveId = ''
                                        this.data.promotionTitle = ''
                                }
                                this.setData({
                                        giveId: this.data.giveId,
                                        promotionTitle: this.data.promotionTitle
                                });
                        }
                },
                /* 点击减号 */
                decnum: function() {
                        var num = this.data.num;
                        // 如果大于1时，才可以减  
                        if (num > 1) {
                                if (this.data.goods.minimum != 0 && num == this.data.goods.minimum) {
                                        wx.showModal({
                                                title: '温馨提示',
                                                content: '该商品' + this.data.goods.minimum + '件起购',
                                        })
                                        return
                                } else {
                                        num--;
                                }
                        }
                        // 只有大于一件的时候，才能normal状态，否则disable状态  
                        var minusStatus = num <= 1 ? 'disabled' : 'normal';

                        // 将数值与状态写回  
                        this.setData({
                                num: num,
                                minusStatus: minusStatus,
                                giveId: this.data.giveId
                        });
                        this.quirey()
                        this.calc()
                },
                /* 点击加号 */
                addnum: function() {
                        var num = this.data.num;
                        if (this.data.goods.minimum != 0 && num < this.data.goods.minimum) {
                                num = num + this.data.goods.minimum
                        } else {
                                if (this.data.maximum != 0 && num == this.data.maximum) {
                                        wx.showModal({
                                                title: '温馨提示',
                                                content: '该商品单人限购' + this.data.maximum + '件',
                                        })
                                        return
                                }
                                // 不作过多考虑自增1  
                                num++;
                        }


                        // 只有大于一件的时候，才能normal状态，否则disable状态  
                        var minusStatus = num < 1 ? 'disabled' : 'normal';
                        // 将数值与状态写回  
                        this.setData({
                                num: num,
                                minusStatus: minusStatus
                        });
                        this.quirey()
                        this.calc()
                },
                /* 输入框事件 */
                numchange: function(e) {
                        var num = e.detail.value;
                        // 将数值与状态写回  
                        this.setData({
                                num: num
                        });
                        var minusStatus = num < 1 ? 'disabled' : 'normal';
                        // 将数值与状态写回  
                        this.setData({
                                num: num,
                                minusStatus: minusStatus,
                                giveId: this.data.giveId
                        });
                        this.quirey()
                        this.calc()
                },
                inputBlur() {
                        if (this.data.num < 1) {
                                this.data.num = 1
                        }
                        if (this.data.maximum != 0 && this.data.num > this.data.maximum) {
                                wx.showModal({
                                        title: '温馨提示',
                                        content: '该商品单人限购' + this.data.maximum + '件',
                                })
                                this.data.num = this.data.maximum
                        } else if (this.data.goods.minimum != 0 && this.data.num < this.data.goods.minimum) {
                                wx.showModal({
                                        title: '温馨提示',
                                        content: '该商品' + this.data.goods.minimum + '件起购',
                                })
                                this.data.num = this.data.goods.minimum
                        }

                        this.setData({
                                num: this.data.num
                        });
                },
                createOrder() {
                        var _this = this
                        http.POST('applet/member/order/create.jhtml', {
                                receiverId: this.data.address.id,
                                id: this.data.product.productId,
                                quantity: this.data.num,
                                xuid: app.globalData.xuid,
                                promotionId: this.data.giveId,
                                shippingMethod: _this.data._shippingMethod,
                                memo: this.data.leave,
                                hopeDate: this.data.timestamp
                        }, function(res) {
                                console.log(res)
                                if (res.type == 'success') {
                                        _this.data.amountPayable = res.data.amountPayable
                                        _this.data.confirm = false
                                        if (res.data.amountPayable == res.data.amountPaid) {
                                                _this.success()
                                        } else {
                                                http.POST('applet/member/order/payment.jhtml', {
                                                                sn: res.data.sn
                                                        }, function(pay) {
                                                                console.log(pay)
                                                                if (pay.type == 'success') {
                                                                        _this.payment(pay.data.sn);
                                                                        //跳转支付
                                                                } else {
                                                                        wx.showModal({
                                                                                content: pay.content,
                                                                                showCancel: false,
                                                                                success: function(res) {
                                                                                        if (res.confirm) {
                                                                                                wx.switchTab({
                                                                                                        url: '/pages/tabBar/order/index',
                                                                                                })
                                                                                        }
                                                                                }
                                                                        });

                                                                }
                                                        },
                                                        function(err) {
                                                                wx.showModal({
                                                                        content: err.content,
                                                                        showCancel: false,
                                                                        success: function(res) {
                                                                                if (res.confirm) {
                                                                                        wx.switchTab({
                                                                                                url: '/pages/tabBar/order/index',
                                                                                        })
                                                                                }
                                                                        }
                                                                });
                                                        })
                                        }
                                } else {
                                        wx.showToast({
                                                icon: "none",
                                                title: res.content,
                                        })
                                }
                        }, function(err) {
                                _this.data.confirm = false
                                wx.showToast({
                                        icon: "none",
                                        title: err.content,
                                })
                        })
                },
                confirm(e) {
                        if (this.data.num <= 0) {
                                wx.showToast({
                                        icon: "none",
                                        title: '请输入数量',
                                })
                                return false
                        }
                        if (utils.isNull(this.data.address)) {
                                wx.showToast({
                                        icon: "none",
                                        title: '请选择地址',
                                })
                                return false
                        }
                        if (utils.isNull(this.data.leave)) {
                                this.data.leave = ''
                        }


                        if (utils.isNull(this.data.timestamp)) {
                                this.data.timestamp = ''
                        }

                        var _this = this
                        if (_this.data.confirm == true) {
                                return
                        }
                        _this.data.confirm = true
                        if (_this.data.calculate.amountPayable == 0) {
                                wx.showModal({
                                        title: '友情提醒',
                                        content: "是否立即购买？",
                                        confirmText: '确定',
                                        concelText: '以后再说',
                                        success: function(res) {
                                                console.log(res);
                                                if (res.confirm) {
                                                        _this.createOrder()
                                                } else {
                                                        _this.data.confirm = false;
                                                        return;
                                                }
                                        }
                                })
                        } else {
                                _this.createOrder()
                        }
                },
                // 立即购买
                buy: function() {
                        var _this = this
                        //登录认证
                        http.authorize("authorize",
                                function(res) {
                                        console.log(res);
                                        if (res.type == 'success') {
                                                // 跳转提交页模式
                                                if (_this.data.type == 'buy') {
                                                        if (_this.data.num <= 0) {
                                                                wx.showToast({
                                                                        icon: "none",
                                                                        title: '请输入数量',
                                                                })
                                                                return false
                                                        }
                                                        if (_this.data.maximum != 0 && _this.data.num > _this.data.maximum) {
                                                                wx.showModal({
                                                                        title: '温馨提示',
                                                                        content: '该商品单人限购' + this.data.maximum + '件',
                                                                })
                                                                return
                                                        } else if (_this.data.goods.minimum != 0 && _this.data.num < _this.data.goods.minimum) {
                                                                wx.showModal({
                                                                        title: '温馨提示',
                                                                        content: '该商品' + this.data.goods.minimum + '件起购',
                                                                })
                                                                return
                                                        }
                                                        wx.navigateTo({
                                                                url: '/pages/cart/submit/index?id=' + _this.data.product.productId + '&quantity=' + _this.data.num + '&promotionId=' + _this.data.giveId + '&shippingMethod=' + _this.data._shippingMethod,
                                                        })
                                                } else if (_this.data.type == 'buyNow') {
                                                        // 不跳转提交页，直接支付
                                                        http.POST("applet/member/order/create.jhtml", {
                                                                        xuid: app.globalData.xuid,
                                                                        id: _this.data.product.productId,
                                                                        quantity: _this.data.num,
                                                                        promotionId: _this.data.giveId,
                                                                        ver: '2.0'
                                                                }, function(res) {
                                                                        console.log(res)
                                                                        if (res.type == "success") {
                                                                                if (res.data.amountPayable == res.data.amountPaid) {
                                                                                        wx.showModal({
                                                                                                content: '订单提交成功',
                                                                                                showCancel: false,
                                                                                                success: function(res) {
                                                                                                        if (res.confirm) {}
                                                                                                }
                                                                                        });
                                                                                        let productData = {
                                                                                                refresh: true
                                                                                        }
                                                                                        app.event.emit('onProductChange' + _this.data.id, productData);
                                                                                        _this.exit();
                                                                                } else {
                                                                                        http.POST('applet/member/order/payment.jhtml?sn=' + res.data.sn, {}, function(pay) {
                                                                                                        if (pay.type == 'success') {
                                                                                                                _this.data.paySn = pay.data.sn;
                                                                                                                _this.payment = _this.selectComponent("#payment");
                                                                                                                _this.payment.paySn(pay.data.sn);
                                                                                                        } else {
                                                                                                                wx.showModal({
                                                                                                                        content: pay.content,
                                                                                                                        showCancel: false,
                                                                                                                        success: function(res) {
                                                                                                                                if (res.confirm) {

                                                                                                                                }
                                                                                                                        }
                                                                                                                });
                                                                                                        }
                                                                                                },
                                                                                                function(err) {
                                                                                                        wx.showModal({
                                                                                                                content: err.content,
                                                                                                                showCancel: false,
                                                                                                                success: function(res) {
                                                                                                                        if (res.confirm) {

                                                                                                                        }
                                                                                                                }
                                                                                                        });
                                                                                                })
                                                                                }
                                                                        } else {
                                                                                wx.showToast({
                                                                                        icon: "none",
                                                                                        title: res.content
                                                                                })
                                                                        }
                                                                },
                                                                function(err) {
                                                                        wx.showToast({
                                                                                icon: "none",
                                                                                title: err.content
                                                                        })
                                                                })
                                                }
                                        } else {
                                                wx.navigateTo({
                                                        url: '/pages/tabBar/login/index',
                                                })
                                        }
                                        _this.exit();
                                        _this.data.hide = true;
                                        _this.setData({
                                                hide: _this.data.hide
                                        })
                                }
                        )
                },
                payComplete: function(e) {
                        console.log(e)
                        let _this = this;
                        if (e.detail.type == 'success') {
                                let productData = {
                                        refresh: true
                                }
                                app.event.emit('onProductChange' + this.data.id, productData);
                                _this.exit();
                        }
                },
                // 加入购物车
                addcart(e) {
                        var _this = this
                        if (_this.data.num <= 0) {
                                wx.showToast({
                                        icon: "none",
                                        title: '请输入数量',
                                })
                                return false
                        }
                        if (this.data.maximum != 0 && _this.data.num > this.data.maximum) {
                                wx.showModal({
                                        title: '温馨提示',
                                        content: '该商品单人限购' + this.data.maximum + '件',
                                })
                                return
                        } else if (this.data.goods.minimum != 0 && _this.data.num < this.data.goods.minimum) {
                                wx.showModal({
                                        title: '温馨提示',
                                        content: '该商品' + this.data.goods.minimum + '件起购',
                                })
                                return
                        }
                        console.log(_this.data.product)
                        http.POST('applet/cart/add.jhtml', {
                                id: _this.data.product.productId,
                                quantity: _this.data.num,
                                promotionId: this.data.giveId
                        }, function(res) {
                                console.log(res)
                                if (res.type == 'success') {
                                        _this.data.confirm = false
                                        let productData = {
                                                productId: _this.data.product.productId,
                                                goodsId: res.data.data.goodsId,
                                                quantity: res.data.data.goodsQuantity
                                        }
                                        app.event.emit('onProductChange' + res.data.data.goodsId, productData);
                                        // 发起通知
                                        app.event.emit("onCartChange", {
                                                quantity: res.data.quantity,
                                                effectivePrice: res.data.effectivePrice
                                        });
                                        _this.setData({
                                                hide: true
                                        })
                                } else {
                                        wx.showToast({
                                                icon: "none",
                                                title: res.content,
                                        })
                                }
                        }, function(err) {
                                _this.data.confirm = false
                                wx.showToast({
                                        icon: "none",
                                        title: err.content,
                                })
                        })
                },
                // 计算总价
                calc() {

                        var _this = this;

                        var addrId = '';
                        if (!utils.isNull(_this.data.address) && !utils.isNull(this.data.address.id)) {
                                addrId = _this.data.address.id;
                        }
                        if (utils.isNull(_this.data.product.productId)) {
                                return;
                        }

                        if (utils.isNull(_this.data.dragonId)) {
                                _this.data.dragonId = 0
                        }
                        http.POST('applet/member/order/calculate.jhtml', {
                                id: _this.data.product.productId,
                                quantity: _this.data.num,
                                shippingMethod: _this.data._shippingMethod,
                                dragonId: _this.data.dragonId,
                                xuid: app.globalData.xuid,
                                promotionId: _this.data.giveId,
                                receiverId: addrId,
                        }, function(res) {
                                console.log(res)
                                if (res.type == 'success') {
                                        _this.data.calculate = res.data

                                        if (utils.isNull(_this.data.address) && !utils.isNull(res.data.receiver)) {
                                                if (!utils.isNull(res.data.receiver.id)) {
                                                        _this.data.address = res.data.receiver

                                                }
                                        }
                                        _this.data.amounts = false
                                        if (res.data.amount <= 0) {
                                                _this.data.amounts = true
                                        }

                                        _this.setData({
                                                calculate: _this.data.calculate,
                                                address: _this.data.address,
                                                amounts: _this.data.amounts
                                        })
                                        console.log(_this.data.calculate)
                                } else {
                                        wx.showToast({
                                                icon: "none",
                                                title: res.content,
                                        })
                                }
                        }, function(err) {
                                wx.showToast({
                                        icon: "none",
                                        title: err.content
                                })
                        })
                },
                activityTap: function(e) {
                        var quantity = e.currentTarget.dataset.quantity
                        console.log(quantity)
                        var index = e.currentTarget.dataset.index
                        this.data.actIndex = index
                        this.data.maximum = e.currentTarget.dataset.maximum
                        console.log(this.data.maximum)
                        if (this.data.maximum != 0 && quantity > this.data.maximum) {
                                quantity = this.data.maximum
                        }
                        this.data.promotionType = e.currentTarget.dataset.type

                        this.data.num = quantity
                        this.setData({
                                giveId: e.currentTarget.dataset.id,
                                num: this.data.num,
                                indexs: index,
                                types: e.currentTarget.dataset.type
                        })
                        // this.calc()
                },
                linkToActivity() {
                        wx.navigateTo({
                                url: '/pages/cart/chooseActive/index?id=' + this.data.product.productId
                        })
                },
                _confirmEvent: function() {
                        this.exit();
                },

                exit: function() {
                        this.data.hide = true;
                        this.data.goodsId = '';
                        this.data.giveId = '';
                        this.data.promotionTitle = ''
                        this.setData({
                                goodsId: this.data.goodsId,
                                hide: this.data.hide,
                                giveId: '',
                                promotionTitle: '',
                                num: 1
                        })
                },

        }
})